package com.example.database;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DatabaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);

        DBAdapter db = new DBAdapter(this);

        try {
            String destPath = "/data/data/"+ getPackageName() + "/databases";

            File f = new File(destPath);
            if(!f.exists()){
                f.mkdir();
                f.createNewFile();
                copyDB(getClass().getClassLoader().getResourceAsStream("assets/"+ "mydb.db"), new FileOutputStream(destPath+"/MyDB"));
            }
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

        db.open();
        Cursor c = db.getAllContacts();
        if(c.moveToFirst()){
            do{
                displayContact(c);
            }while (c.moveToNext());
        }

        db.close();
    }

    public void copyDB(InputStream inputStream, OutputStream outputStream) throws IOException{
        byte[] buffer = new byte[1024];

        int length;

        while ((length = inputStream.read(buffer)) > 0){
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        outputStream.close();
    }

    public void displayContact(Cursor c){
        Toast.makeText(this, "id: "+ c.getString(0) + "\n" + "Name: " + c.getString(1) + "\n" + "Email: " + c.getString(2), Toast.LENGTH_LONG).show();
    }
}
